package com.ssm.zy.interceptor;

import com.ssm.zy.common.exception.UnauthenticatedException;
import com.ssm.zy.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //设置白名单
        List<String> whiteList = new ArrayList();
        whiteList.add("/user/login.do");
        whiteList.add("/user/register.do");
        whiteList.add("/user/checkUsername.do");
        whiteList.add("/user/checkPhone.do");
        whiteList.add("/user/findCityByParentId.do");
        whiteList.add("/common/fileUpload.do");
        whiteList.add("/post/viewerCheck.do");
        whiteList.add("/post/getLabel.do");

        //白名单放行
        if (whiteList.contains(request.getRequestURI())){
            return true;
        }

        //1.截胡请求,获取请求头token信息
        String token = request.getHeader("Authorization");
        //2. 判断token是否存在(用户是否登录)
        if (!StringUtils.isEmpty(token)) {
            //2.1 如果存在，则解析token，获取claims并存储在request中
            Claims claims = jwtUtil.parseJWT(token);
            if (claims != null) {
                request.setAttribute("user_claims",claims);
                return true;
            }
        }
        //2.2 如果不存在，则抛出'用户未登陆'异常
        throw new UnauthenticatedException();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
